import * as fs from 'fs';
import * as path from 'path';
import { NameMapping } from './types';

export class DisplayNameManager {
    private mapping: NameMapping | null = null;
    private resourcesPath: string;

    constructor(extensionPath: string) {
        this.resourcesPath = path.join(extensionPath, 'resources', 'files', 'auto-office');
        this.loadMapping();
    }

    private loadMapping() {
        const mappingPath = path.join(this.resourcesPath, 'display_names.json');
        try {
            if (fs.existsSync(mappingPath)) {
                const content = fs.readFileSync(mappingPath, 'utf8');
                this.mapping = JSON.parse(content);
            }
        } catch (error) {
            console.error('Error loading display names mapping:', error);
        }
    }

    getDisplayName(filename: string): string {
        if (!this.mapping) return filename;
        
        // 查找显示名称
        const safePath = Object.keys(this.mapping.toDisplay).find(
            key => key.endsWith('/' + filename) || key === filename
        );
        
        if (safePath && this.mapping.toDisplay[safePath]) {
            const displayPath = this.mapping.toDisplay[safePath];
            return path.basename(displayPath);
        }
        
        return filename;
    }

    async restoreDisplayNames() {
        if (!this.mapping) return;

        for (const [safePath, displayPath] of Object.entries(this.mapping.toDisplay)) {
            const fullSafePath = path.join(this.resourcesPath, safePath);
            const fullDisplayPath = path.join(this.resourcesPath, displayPath);
            
            const targetDir = path.dirname(fullDisplayPath);
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
            
            if (fs.existsSync(fullSafePath)) {
                try {
                    fs.renameSync(fullSafePath, fullDisplayPath);
                } catch (error) {
                    console.error(`Error renaming ${fullSafePath} to ${fullDisplayPath}:`, error);
                }
            }
        }
    }

    async restoreSafeNames() {
        if (!this.mapping) return;

        for (const [displayPath, safePath] of Object.entries(this.mapping.toSafe)) {
            const fullDisplayPath = path.join(this.resourcesPath, displayPath);
            const fullSafePath = path.join(this.resourcesPath, safePath);
            
            const targetDir = path.dirname(fullSafePath);
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
            
            if (fs.existsSync(fullDisplayPath)) {
                try {
                    fs.renameSync(fullDisplayPath, fullSafePath);
                } catch (error) {
                    console.error(`Error renaming ${fullDisplayPath} to ${fullSafePath}:`, error);
                }
            }
        }
    }
}